/*
 * 描述 数据源配置接口
 * Create by cy on 2025/06/16
 * */

const express = require("express");
const router = express.Router();
const db = require("../../db");

router.get("/list", (req, res) => {
  let s = `
    SELECT 
      mp.*, 
      ds.ds_name AS data_source_name, 
      ds.ds_code, 
      ds.ds_type
    FROM 
      express.module_params mp
    LEFT JOIN 
      express.data_source_configs ds
    ON 
      mp.data_source_id = ds.id
  `;

  db.query(s, (err, result) => {
    if (err) throw err;
    res.json({
      data: result,
    });
  });
});
//新增接口
router.post("/create", (req, res) => {
  const { module_name, description, data_source_id, created_by } = req.body;
  const sql = `INSERT INTO module_params 
    (module_name, description, data_source_id, created_by) 
    VALUES (?, ?, ?, ?)`;

  db.query(
    sql,
    [module_name, description, data_source_id, created_by],
    (error, result) => {
      if (error) {
        console.log(error);
        res.status(500).json({ error: error.message });
        return;
      }
      res.json({ id: result.insertId });
    }
  );
});
//修改接口
router.post("/update", (req, res) => {
  const { id, module_name, description, data_source_id, created_by } = req.body;
  const sql = `UPDATE module_params SET module_name=?, description=?, data_source_id=?, created_by=? WHERE id=?`;
  db.query(
    sql,
    [module_name, description, data_source_id, created_by, id],
    (error, result) => {
      if (error) throw error;
      res.json({});
    }
  );
});
//删除接口
router.post("/delete", (req, res) => {
  const { id } = req.body;
  const sql = `DELETE FROM module_params WHERE id=?`;
  db.query(sql, [id], (error, result) => {
    if (error) throw error;
    res.json({});
  });
});
module.exports = router;
